#!/bin/bash -e

PACKAGE_DIR=/var/vcap/packages/postgres-13

HOST=<%= p("postgres.listen_address") %>
PORT=<%= p("postgres.port") %>
USER='<%= p("postgres.user") %>'
PASSWORD='<%= p("postgres.password") %>'
DBNAMES=(<%= p("postgres.additional_databases").join(" ") %>)
DBNAMES+=('<%= p("postgres.database") %>')

export LD_LIBRARY_PATH="$PACKAGE_DIR/lib:$LD_LIBRARY_PATH"

# wait for database to be running
for i in $( seq 0 30 ); do
  if /var/vcap/packages/postgres-13/bin/oid2name -H ${HOST} -U ${USER} -d postgres -q ; then
    break
  fi

  sleep 1
done

set +e

for DBNAME in "${DBNAMES[@]}"; do
  echo "Trying to create database $DBNAME..."
  $PACKAGE_DIR/bin/createdb $DBNAME -h $HOST -p $PORT -U vcap
  if [ $? != 0 ]; then
    echo "Warning: failed to create $DBNAME; ignoring"
  fi

  echo "Trying to create user..."
  $PACKAGE_DIR/bin/psql -d $DBNAME -h $HOST -p $PORT -U vcap -c "create role \"$USER\" NOSUPERUSER LOGIN INHERIT CREATEDB"

  echo "Trying to alter user (to change password)..."
  $PACKAGE_DIR/bin/psql -d $DBNAME -h $HOST  -p $PORT -U vcap -c "alter role \"$USER\" with password '$PASSWORD'"
done
